<script setup lang="ts">
import { ref, computed } from 'vue'
import { getRoleListService, setUserRoleService } from '@/apis/acl/user'
import type { User, RoleListResponseData, RoleList } from '@/apis/acl/user/type'

const drawerVisible = ref<boolean>(false)

// 全选
const checkAll = ref<boolean>(false)
const allRoles = ref<RoleList>([])
const checkedRoles = ref<RoleList>([])
const userId = ref<string>()
// 获取角色列表
const getRoleList = async (id: string) => {
  const res: RoleListResponseData = await getRoleListService(id)
  allRoles.value = res.data.allRolesList
  checkedRoles.value = res.data.assignRoles
}
// 角色姓名
const username = ref<string>('')
const assignRole = (row: User) => {
  drawerVisible.value = true
  userId.value = row.id
  getRoleList(row.id as string)
  username.value = row.username
}

// 确定
const emits = defineEmits(['reload'])
const onConfirm = async () => {
  drawerVisible.value = false
  await setUserRoleService({
    userId: userId.value as string,
    roleIdList: checkedRoles.value.map((item) => item.id) as string[]
  })
  await ElMessage.success('分配成功')
  emits('reload')
}

defineExpose({
  assignRole
})
const isIndeterminate = computed(
  () =>
    checkedRoles.value.length &&
    checkedRoles.value.length < allRoles.value.length
)
// 选择框
const onCheckAll = (val: boolean) => {
  checkedRoles.value = val ? allRoles.value : []
}
// 选择
const onChecked = (val: RoleList) => {
  checkAll.value = val.length === allRoles.value.length
}
</script>

<template>
  <el-drawer v-model="drawerVisible" title="分配角色">
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input disabled v-model="username"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            @change="onCheckAll"
            :indeterminate="isIndeterminate"
            >全选</el-checkbox
          >
          <el-checkbox-group v-model="checkedRoles" @change="onChecked">
            <el-checkbox
              v-for="item in allRoles"
              :key="item.id"
              :label="item.roleName"
              :value="item"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="onConfirm">确定</el-button>
    </template>
  </el-drawer>
</template>
